
import sys
import random
from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QLabel, 
                            QVBoxLayout, QGridLayout, QFrame, QMessageBox,
                            QScrollArea)
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QFont

from database import GameDatabase

# 删除 from game import Game 这行

class StartMenu(QWidget):
    def __init__(self):
        super().__init__()
        self.db = GameDatabase()
        self.initUI()

    def initUI(self):
        """初始化开始菜单界面"""
        self.setWindowTitle('哄女朋友开心游戏')
        self.setGeometry(300, 300, 600, 400)
        
        layout = QVBoxLayout()
        
        # 创建标题
        title = QLabel('哄女朋友开心游戏', self)
        title.setAlignment(Qt.AlignCenter)
        title.setFont(QFont('Arial', 24, QFont.Bold))
        title.setStyleSheet('color: #FF69B4; margin: 20px;')
        
        # 创建游戏说明
        description = QLabel(
            '游戏规则：\n'
            '1. 赵茜现在心情不太好\n'
            '2. 通过不同的行动来哄女朋友开心\n'
            '3. 心情值达到100分即获胜\n'
            '4. 心情值降到0分游戏结束\n'
            '\n祝你好运！'
        )
        description.setAlignment(Qt.AlignCenter)
        description.setFont(QFont('Arial', 12))
        description.setStyleSheet('color: #696969; margin: 20px;')
        
        # 定义按钮样式
        button_style = '''
            QPushButton {
                background-color: #FFB6C1;
                border: 2px solid #FF69B4;
                border-radius: 15px;
                padding: 10px;
                font-size: 16px;
                color: white;
                min-width: 200px;
                margin: 10px;
            }
            QPushButton:hover {
                background-color: #FF69B4;
            }
        '''
        
        # 创建按钮
        start_button = QPushButton('开始游戏', self)
        history_button = QPushButton('游戏记录', self)
        exit_button = QPushButton('退出游戏', self)
        
        # 应用按钮样式
        start_button.setStyleSheet(button_style)
        history_button.setStyleSheet(button_style)
        exit_button.setStyleSheet(button_style)
        
        # 连接按钮信号
        start_button.clicked.connect(self.start_game)
        history_button.clicked.connect(self.show_game_history)
        exit_button.clicked.connect(self.close)
        
        layout.addWidget(title)
        layout.addWidget(description)
        layout.addStretch()
        layout.addWidget(start_button)
        layout.addWidget(history_button)
        layout.addWidget(exit_button)
        layout.addStretch()
        
        self.setLayout(layout)

    def start_game(self):
        """启动新游戏"""
        self.game = Game()
        self.game.show()
        self.close()

    def show_game_history(self):
        """显示游戏历史记录"""
        history = self.db.get_all_games()
        if not history:
            QMessageBox.information(self, '游戏记录', '还没有游戏记录哦！')
            return
        
        # 创建历史记录对话框
        history_dialog = QMessageBox(self)
        history_dialog.setWindowTitle('游戏记录')
        history_dialog.setIcon(QMessageBox.Information)
        history_dialog.setStyleSheet('''
            QMessageBox {
                background-color: #FFF0F5;
            }
            QLabel {
                color: #8B4513;
                font-size: 14px;
            }
        ''')
        
        # 创建可滚动的文本区域
        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        scroll.setStyleSheet('background-color: #FFF8DC; border: none;')
        
        # 创建内容部件
        content = QWidget()
        layout = QVBoxLayout(content)
        layout.setSpacing(15)
        layout.setContentsMargins(20, 20, 20, 20)  # 增加内边距

        # 格式化历史记录
        for game in history:
            game_info = QLabel(
                f"⏰ 时间：{game[1]}\n"
                f"💖 最终心情值：{game[2]}\n" 
                f"🏁 结果：{game[3]}\n"
            )
            game_info.setStyleSheet('''
                background-color: #FFE4E1;
                border-radius: 10px;
                padding: 15px;
                color: #FF1493;
                font-size: 16px;
                min-width: 550px;  # 增加最小宽度
            ''')
            layout.addWidget(game_info)
            
            # 获取互动记录
            interactions = self.db.get_session_interactions(game[0])
            for interaction in interactions:
                interaction_info = QLabel(
                    f"   🎭 行动：{interaction[2]}\n"
                    f"   💬 反应：{interaction[3]}\n"
                    f"   📈 心情变化：{interaction[4]}\n"
                )
                interaction_info.setStyleSheet('''
                    color: #8B4513;
                    margin-left: 20px;
                    background-color: #FFF0F5;
                    border-radius: 8px;
                    padding: 10px;
                    min-width: 500px;  # 增加最小宽度
                ''')
                layout.addWidget(interaction_info)
            
            # 添加分隔线
            separator = QFrame()
            separator.setFrameShape(QFrame.HLine)
            separator.setStyleSheet('''
                color: #FF69B4;
                margin: 20px 0;
            ''')  # 增加上下边距
            layout.addWidget(separator)

        # 设置滚动区域内容
        scroll.setWidget(content)
        scroll.setMinimumSize(700, 500)  # 增大滚动区域尺寸
        
        # 将滚动区域添加到对话框
        history_dialog.layout().addWidget(scroll, 0, 0, 1, history_dialog.layout().columnCount())
        history_dialog.setMinimumSize(800, 600)  # 增大对话框最小尺寸
        history_dialog.exec_()

class Game(QWidget):
    def __init__(self):
        super().__init__()
        self.db = GameDatabase()
        self.game_id = self.db.start_new_game()
        self.initUI()
        self.initGame()

    def initUI(self):
        """初始化游戏界面"""
        self.setWindowTitle('哄女朋友开心游戏')
        self.setGeometry(300, 300, 800, 600)  # 增大窗口尺寸
        self.setStyleSheet('background-color: #FFF0F5;')  # 设置背景颜色
        
        # 创建心情值显示
        self.mood_label = QLabel('💖 当前心情值: 50', self)
        self.mood_label.setAlignment(Qt.AlignCenter)
        self.mood_label.setFont(QFont('Arial', 24, QFont.Bold))
        self.mood_label.setStyleSheet('''
            color: #FF1493;
            background-color: #FFE4E1;
            border-radius: 15px;
            padding: 20px;
            margin: 20px;
        ''')
        
        # 创建状态显示
        self.status_label = QLabel('赵茜现在心情不太好...', self)
        self.status_label.setAlignment(Qt.AlignCenter)
        self.status_label.setFont(QFont('Arial', 16))
        self.status_label.setStyleSheet('''
            color: #8B4513;
            background-color: #FFF8DC;
            border-radius: 10px;
            padding: 15px;
            margin: 10px;
        ''')
        
        # 定义按钮样式
        button_style = '''
            QPushButton {
                background-color: #FF69B4;
                border: 2px solid #FF1493;
                border-radius: 20px;
                padding: 20px;
                font-size: 18px;
                color: white;
                min-width: 200px;
                margin: 15px;
            }
            QPushButton:hover {
                background-color: #FF1493;
                border-color: #FF69B4;
            }
        '''
        
        # 创建按钮
        self.button_flower = QPushButton('🌸 送花', self)
        self.button_joke = QPushButton('😂 讲笑话', self)
        self.button_apologize = QPushButton('🙏 道歉', self)
        self.button_hug = QPushButton('🤗 拥抱', self)
        self.button_gift = QPushButton('🎁 买礼物', self)
        self.button_tease = QPushButton('😈 气人', self)
        
        # 应用按钮样式
        for button in [self.button_flower, self.button_joke, self.button_apologize,
                      self.button_hug, self.button_gift, self.button_tease]:
            button.setStyleSheet(button_style)
        
        # 连接按钮信号（修改这部分）
        self.button_flower.clicked.connect(lambda: self._handle_action('🌸 送花'))
        self.button_joke.clicked.connect(lambda: self._handle_action('😂 讲笑话'))
        self.button_apologize.clicked.connect(lambda: self._handle_action('🙏 道歉'))
        self.button_hug.clicked.connect(lambda: self._handle_action('🤗 拥抱'))
        self.button_gift.clicked.connect(lambda: self._handle_action('🎁 买礼物'))
        self.button_tease.clicked.connect(lambda: self._handle_action('😈 气人'))
        
        # 创建按钮布局
        button_layout = QGridLayout()
        button_layout.addWidget(self.button_flower, 0, 0)
        button_layout.addWidget(self.button_joke, 0, 1)
        button_layout.addWidget(self.button_apologize, 0, 2)
        button_layout.addWidget(self.button_hug, 1, 0)
        button_layout.addWidget(self.button_gift, 1, 1)
        button_layout.addWidget(self.button_tease, 1, 2)
        
        # 主布局
        layout = QVBoxLayout()
        layout.addWidget(self.mood_label)
        layout.addWidget(self.status_label)
        layout.addLayout(button_layout)
        layout.addStretch()
        
        self.setLayout(layout)

    def _handle_action(self, action):
        """处理玩家行动"""
        responses = {
            '🌸 送花': [
                ('赵茜收到花后开心地蹦跳起来！', 10),
                ('赵茜说："你送的花好漂亮，我最喜欢这个颜色了~"', 8),
                ('赵茜开心地把花插在了花瓶里："谢谢你记得给我买花~"', 5),
                ('赵茜说："上周你才送过花...不过我还是很开心！"', -3),
                ('赵茜叹了口气："你每次都是送花，能不能换点别的..."', -8)
            ],
            '😂 讲笑话': [
                ('赵茜被你的笑话逗得前仰后合！', 8),
                ('赵茜笑得直拍桌子："你怎么这么可爱啊！"', 5),
                ('赵茜捂着嘴偷笑："你好幼稚~不过我喜欢~"', 3),
                ('赵茜勉强笑了笑："这个笑话我好像在抖音上看过..."', -5),
                ('赵茜翻了个白眼："一点都不好笑！"', -10)
            ],
            '🙏 道歉': [
                ('赵茜感动地说："你知道错了就好~抱抱！"', 5),
                ('赵茜破涕为笑："你这样认错的样子真可爱~"', -10),
                ('赵茜说："哼，这次原谅你了，下次不许这样了！"', -15),
                ('赵茜叹了口气："你总是这样..."', -8),
                ('赵茜说："光说对不起有什么用！"', -12)
            ],
            '🤗 拥抱': [
                ('赵茜幸福地依偎在你怀里："你的怀抱最温暖了~"', 12),
                ('赵茜紧紧地回抱住你："最喜欢和你抱抱了！"', 8),
                ('赵茜轻轻回抱了你一下，脸红红的', 5),
                ('赵茜小声说："等会再抱好不好..."', -5),
                ('赵茜躲开了："现在不想抱抱..."', -10)
            ],
            '🎁 买礼物': [
                ('赵茜惊喜地跳起来："啊！这就是我想要的那个！"', 15),
                ('赵茜开心地说："谢谢你记得我喜欢什么~"', 10),
                ('赵茜害羞地说："其实你不用总是给我买东西的..."', 5),
                ('赵茜勉强笑了笑："谢谢...不过我更希望你能陪陪我"', -5),
                ('赵茜说："你都没问问我想要什么就买了..."', -10)
            ],
            '😈 气人': [
                ('赵茜气得跺脚："你故意惹我生气是不是！"', -20),
                ('赵茜眼眶红了："你怎么能这样对我..."', -15),
                ('赵茜转身就走："不想理你了！"', -25),
                ('赵茜摔门而出："今晚你睡沙发！"', -30),
                ('赵茜沉默了很久最后说："我们冷静几天吧"', -40)
            ]
        }
        
        # 获取按钮文本（去掉emoji）
        # 修正 action_text 的提取方式
        action_text = action.split()[1]  # 使用 split() 而不是 split(' ')
        response, mood_change = random.choice(responses[action])
        self.mood_value = max(0, min(100, self.mood_value + mood_change))
        self.mood_label.setText(f'💖 当前心情值: {self.mood_value}')
        self.status_label.setText(response)  # 确保这行代码存在
        
        # 记录互动（使用完整按钮文本）
        self.db.add_interaction(self.game_id, action, response, mood_change)  # 修改这里
        
        # 检查游戏是否结束
        if self.mood_value <= 0:
            self.auto_mood_timer.stop()  # 修改这里
            self.action_timer.stop()     # 新增这行
            self.db.end_game(self.game_id, self.mood_value, "失败")
            QMessageBox.information(self, "游戏结束", "女朋友生气走了...")
            self._return_to_main_menu()
        elif self.mood_value >= 100:
            self.auto_mood_timer.stop()  # 修改这里
            self.action_timer.stop()     # 新增这行
            self.db.end_game(self.game_id, self.mood_value, "成功")
            QMessageBox.information(self, "游戏结束", "成功哄开心啦！")
            self._return_to_main_menu()

    def initGame(self):
        """初始化游戏状态"""
        self.mood_value = 50
        # 创建两个计时器
        self.action_timer = QTimer(self)  # 操作间隔计时器
        self.action_timer.setSingleShot(True)
        self.action_timer.timeout.connect(self._on_idle_timeout)
        
        self.auto_mood_timer = QTimer(self)  # 原有自动减分计时器
        self.auto_mood_timer.timeout.connect(self._handle_timeout)
        self.auto_mood_timer.start(10000)  # 每10秒自动减分

    def _handle_timeout(self):
        """处理计时器超时事件"""
        self.mood_value -= 5  # 每次超时减少5点心情值
        self.mood_label.setText(f'💖 当前心情值: {self.mood_value}')
                # 新增状态提示和记录
        responses = [
            "赵茜看了看表：'你还要让我等多久？'",
            "赵茜皱眉说：'你最近越来越不关心我了...'",
            "赵茜无聊地刷着手机：'你忙你的吧...'",
            "赵茜失望地说：'连陪我说话的时间都没有了吗...'",
            "赵茜的耐心正在逐渐消失..."
        ]
        response = random.choice(responses)
        self.status_label.setText(response)  # 添加这行
        self.db.add_interaction(self.game_id, "自动减分", response, -5)  # 添加这行
        
        # 检查游戏是否结束
        if self.mood_value <= 0:
            self.auto_mood_timer.stop()
            QMessageBox.information(self, "游戏结束", "女朋友生气走了...")
            self._end_game("失败", "长期冷落导致关系破裂...")
        elif self.mood_value >= 100:
            self.auto_mood_timer.stop()
            QMessageBox.information(self, "游戏结束", "成功哄开心啦！")
            self._end_game("成功", "坚持不懈终获芳心")

    def _on_idle_timeout(self):
        """处理操作间隔超时"""
        if self.mood_value <= 0:
            return
            
        self.mood_value = max(0, self.mood_value - 2)
        self.mood_label.setText(f'💖 当前心情值: {self.mood_value}')
        
        responses = [
            "赵茜看起来有点不耐烦了...",
            "赵茜生气地说：'你是不是不想理我？'", 
            "赵茜撅着嘴：'你都不陪我...'",
            "赵茜叹了口气：'你总是这样...'",
            "赵茜默默地玩着手机，不看你..."
        ]
        self.status_label.setText(random.choice(responses))
        
        self.db.add_interaction(self.game_id, "等待超时", "操作间隔过长", -2)
        
        if self.mood_value <= 0:
            self._end_game("失败", "女朋友等得不耐烦走了...")  # 保持原有正确调用

    def _end_game(self, result, message):
        """统一处理游戏结束"""
        self.action_timer.stop()
        self.auto_mood_timer.stop()
        self.db.end_game(self.game_id, self.mood_value, result)
        QMessageBox.information(self, "游戏结束", message)
        self._return_to_main_menu()

    def _return_to_main_menu(self):
        """返回主菜单"""
        self.close()
        self.main_menu = StartMenu()
        self.main_menu.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    start_menu = StartMenu()
    start_menu.show()
    sys.exit(app.exec_())